<?php





namespace app\shop\model;



use app\crm\model\FollowRecord;

use app\admin\model\Common;

use Kingdee\Kingdee;

use think\facade\Db;

use think\model\concern\SoftDelete;

use app\common\traits\ActionRecordTrait;

use app\shop\model\RefundPayModel;

use app\shop\model\AddOrderLog;


/**

 * 支付模型

 * @package app\shop\model

 * @author LIU

 * @create 2021-10-01

 */
class PayModel extends Common
{
    use ActionRecordTrait;



    /**

     * 表名

     * @var string

     */

    protected $name = 'shop_refund_order';

    protected $defaultSoftDelete = 0;

    /**

     * 获取sku信息

     * @return \think\model\relation\hasOne

     * @author SL

     * @create 2021-05-27 15:04

     */

    public function orderGoods()

    {

        return $this->hasOne(Goods::class,'id');

    }

    /**

     * 请求被扫码支付

     * @param  array $request 请求参数

     * @return array

     * @author LIU

     * @create 2021-10-26

     */

    public function payBox($request)
    {

        // echo "<pre>";
        // print_r($request);
        // echo "</pre>";
        // exit;

        try {

            $order_id = $request['order_id'] ?? 0;

            $authcode  = $request['authCode'] ?? 0;

			$shopIds  = $request['shopIds'] ?? 0;

            if(!empty($order_id) && !empty($authcode)){

                $where = [];

                array_push($where,['id','=',$order_id]);

                $oredr_info = Db::name('shop_refund_order')->where($where)->find();


				$shop_where = [];

				array_push($shop_where,['shop_id','=',$shopIds]);

				$shop_info = Db::name('shop')->where($shop_where)->find();


                if($oredr_info['shanghu_type'] == '1'){
                    // 公户

                    $cusid = $shop_info['shop_gonghu_cusid'];

                    $appid = $shop_info['shop_gonghu_appid'];

                    $private_key = $shop_info['shop_gonghu_privateKey'];

                }else{
                    // 私户

                    $cusid = $shop_info['shop_sihu_cusid'];

                    $appid = $shop_info['shop_sihu_appid'];

                    $private_key = $shop_info['shop_sihu_privateKey'];

                }

                $payRequest = [

                    'pay_amount' =>$oredr_info['pay_amount'],

                    'refund_order_no' => $oredr_info['refund_order_no'],

                    'authcode' => $authcode,

                    'description' => $oredr_info['description'],

                    'cusid' => $cusid,

                    'appid' => $appid,

                    'private_key' => $private_key,

                ];

                /* echo "<pre>";
                print_r($payRequest);
                echo "</pre>";
                exit; */

                $RefundPay = new RefundPayModel();

                $res = $RefundPay->scanqrpay($payRequest);
                // $res['code'] = '0000';

                // echo "扫码接口返回值：";
                // echo "<pre>";
                // print_r($res);
                // echo "</pre>";
				// exit;

                if($res['code'] == '0000'){
                    // echo "支付成功1111！！！";echo '<br/>';
                    $king_res = $this->changeBalance($oredr_info); // 下推云星空

                    // var_dump($king_res);
                    // exit;

                    if($king_res === true){

                        $this->changeOederType($oredr_info['id']); // 修改订单支付状态

                        // 生成收款记录
                        $addLogModel = new AddOrderLog();

                        $addLogModel->addData($oredr_info['uid'],$oredr_info['shop_id'],$oredr_info['refund_order_no'],$oredr_info['deal_time'],'3');

                        // $this->error = '支付成功！';

                        // return true;

                    }else{

                        $this->error = $king_res;

                        return false;

                    }



                }else{
                    //echo "支付失败！！！";

                    $this->error = $res['msg'];

                    return false;
                }


            }else{
                // echo "数据异常，请重新支付！";

                $this->error = '数据异常，请重新支付！';

                return false;
            }

            Db::commit();

            $this->error = '支付成功！';

            return true;

        }catch (\Exception $e) {

            Db::rollback();

            $this->error = $e->getMessage();

            return false;

        }

        // return $request;
    }

    /**

     * 请求支付链接

     * @param  array $request 请求参数

     * @return array

     * @author yangpeng

     * @create 2022-07-12

     */
    public function getPayUrl($request)
    {

        $order_id = $request['order_id'] ?? 0;

		$shopIds  = $request['shopIds'] ?? 0;

        $where = [];

        array_push($where,['id','=',$order_id]);

        $oredr_info = Db::name('shop_refund_order')->where($where)->find();

        $customer_info = Db::name('customer')->where('id',$oredr_info['uid'])->find();

        $shop_where = [];

        array_push($shop_where,['shop_id','=',$shopIds]);

        $shop_info = Db::name('shop')->where($shop_where)->find();

        if($oredr_info['shanghu_type'] == '1'){
            // 公户

            $cusid = $shop_info['shop_gonghu_cusid'];

            $appid = $shop_info['shop_gonghu_appid'];

            $private_key = $shop_info['shop_gonghu_privateKey'];

        }else{
            // 私户

            $cusid = $shop_info['shop_sihu_cusid'];

            $appid = $shop_info['shop_sihu_appid'];

            $private_key = $shop_info['shop_sihu_privateKey'];

        }

        $payRequest = [

            'pay_amount' =>$oredr_info['pay_amount'],

            'refund_order_no' => $oredr_info['refund_order_no'],

            'type' => $request['type'],

            'description' => $oredr_info['description'],

            'cusid' => $cusid,

            'appid' => $appid,

            'private_key' => $private_key,

            'shop_name' => '欣奕除疤'.$shop_info['city_name'].$shop_info['shop_name'],

            'shop_id' => $shopIds,

            'shanghu_type' => $oredr_info['shanghu_type'],

            'customer_name' => $customer_info['customer_name'],

            'time' => date('Y-m-d',time()),

        ];

        // $RefundPay = new RefundPayModel();

        // $res = $RefundPay->pay($payRequest);
        // $res = $RefundPay->payh5($payRequest);

        return $payRequest;
    }

    /**

     * 扫码支付返回结果

     * @param  array $request 请求参数

     * @return array

     * @author yangpeng

     * @create 2022-07-12

     */
    public function getPayBack($request)
    {
        // echo '支付返回值：'.$request;

        $data = explode('&',$request);

        $one = [];
        foreach ($data as $key => $value) {
            $r = explode('=',$value);
            $one[$r[0]] = $r[1];
        }

        $refund_order_no = $one['cusorderid'] ?? 0;

        // echo "订单单号：".$refund_order_no;
        // echo "<br/>";

        $where = [];

        array_push($where,['refund_order_no','=',$refund_order_no]);

        $oredr_info = Db::name('shop_refund_order')->where($where)->find();

        // echo "<pre>";
        // print_r($oredr_info);
        // echo "</pre>";
        /////////////////////////////////////////////////////////////////////////////////////////////
        $mark1 = bcadd($oredr_info['mark1'],1,0);

        $whereMark1 = [];

        array_push($whereMark1,['id','=',$oredr_info['id']]);

        $save1 = [
            'mark1' => $mark1,
        ];

        Db::name('shop_refund_order')->where($whereMark1)->update($save1);
        //////////////////////////////////////////////////////////////////////////////////////////////


        if($oredr_info){
            // echo "go on";
            // echo "<br/>";

            if($oredr_info['is_pay'] == 0){

                /////////////////////////////////////////////////////////////////////////////////////////////
                $mark2 = bcadd($oredr_info['mark2'],1,0);

                $whereMark2 = [];

                array_push($whereMark2,['id','=',$oredr_info['id']]);

                $save2 = [
                    'mark2' => $mark2,
                ];

                Db::name('shop_refund_order')->where($whereMark2)->update($save2);
                //////////////////////////////////////////////////////////////////////////////////////////////

                if($one['trxstatus'] == '0000'){

                    // echo "one";echo "<br/>";
                    /////////////////////////////////////////////////////////////////////////////////////////////
                    $mark3 = bcadd($oredr_info['mark3'],1,0);

                    $whereMark3 = [];

                    array_push($whereMark3,['id','=',$oredr_info['id']]);

                    $save3 = [
                        'mark3' => $mark3,
                    ];

                    Db::name('shop_refund_order')->where($whereMark3)->update($save3);
                    //////////////////////////////////////////////////////////////////////////////////////////////

                    // 开始下推金蝶
                    $king_res = $this->changeBalance($oredr_info); // 下推云星空

                    if($king_res === true){

                        // echo "two";echo "<br/>";

                        $this->changeOederType($oredr_info['id']); // 修改订单支付状态

                        // $where = [];

                        // array_push($where,['id','=',$order_id]);

                        // $save2 = [
                        //     'pay_error' => '支付成功！',
                        // ];

                        // $res = Db::name('shop_refund_order')->where($where)->update($save2);

                        // echo "流程完成";

                        // echo "<pre>";
                        // print_r($oredr_info);
                        // echo "</pre>";

                        // 生成收款记录
                        // $addLogModel = new AddOrderLog();

                        // $addLogModel->addData($oredr_info['uid'],$oredr_info['shop_id'],$oredr_info['refund_order_no'],$oredr_info['deal_time'],'3');

                    }else {

                        // 金蝶推送失败

                        $where = [];

                        array_push($where,['id','=',$order_id]);

                        $save2 = [
                            'pay_error' => '金蝶推送失败',
                        ];

                        $res = Db::name('shop_refund_order')->where($where)->update($save2);

                        return 'error';

                    }

                }else{

                    // echo $one['trxstatus'];
                    // exit;
                    $where = [];

                    array_push($where,['id','=',$order_id]);

                    $save2 = [
                        'pay_error' => '支付失败',
                    ];

                    $res = Db::name('shop_refund_order')->where($where)->update($save2);

                    return 'error';

                }


                // echo "收款成功！！！";

                return 'success';
            }

        }else{
            // echo "order loss";

            return 'error';
        }
    }

    /**

     * 支付成功调整订单支付状态

     * @param  array $request 请求参数

     * @return array

     * @author yangpeng

     * @create 2022-07-12

     */
    public function changeOederType($order_id)
    {
        $where = [];

        array_push($where,['id','=',$order_id]);

        $save = [

            'is_pay' => '1',

            'is_pay_time' => time(),

            'pay_error' => '支付成功！',

        ];

        $res = Db::name('shop_refund_order')->where($where)->update($save);

        // var_dump($res);
    }


    /**

     * 支付成功调整顾客预存推送云星空

     * @param  array $request 请求参数

     * @return array

     * @author yangpeng

     * @create 2022-07-12

     */
    public function changeBalance($data)
    {

        // 开启事务
        Db::startTrans();

        try {

            /* echo '<pre>';
            print_r($data);
            echo '客户预存信息修改到此接收----55555';echo '<br/>'; */
            $pay_price = $data['pay_amount'];

            $gift_price = $data['gift_amount'];

            //----------------------------处理客户预存信息-----------------------------

            $customerModel = new \app\crm\model\Customer();

            $customer_id = $data['uid']; // 顾客id

            $balanceData   = [                // 余额变更数据集

                'change_type'  => '1',      // 变动类型 1:增加 2:减少

                'change_money' => $pay_price,      // 变更的本金

                'complimentary_money' => $gift_price,  // 变更的赠金

                'balance_category_id' => $data['business_type'] // 变更的余额的类型 1:疤痕 2:项目

            ];

            $newOrderData  = [   // 新单变更数据集

                'cj_time'  => ($data['type']==3 && $data['order_type']==1 && $pay_price>=500)?$data['deal_time']:0,     // 成交时间-时间戳

                'cj_money'    => $pay_price,    // 成交金额

                'cj_order_id' => $data['id'], // 成交的订单单号

            ];

            $orderInfo     = [       // 本次需要新增的订单金额

                'order_amount' => $pay_price, // 本次订单金额

                'order_time'   => $data['type']==3 ? $data['deal_time'] : 0,   // 本次订单的时间-时间戳

            ];

            $member_products = 0; // 购买了几次会员商品

            $yhjOrderInfo  = [    // 本次需要处理的优惠卷

                'yhj_id '     => 0,      // 本次优惠卷的id

                'order_id  '  => 0,   // 本次订单的id

                'operator_id' => 0,  // 核销人的id

            ];

            $deal_time = date('Y-m-d',$data['deal_time']);


            $aaa = $customerModel->processingFunds($customer_id,$balanceData,$deal_time,$newOrderData,$orderInfo,$yhjOrderInfo,$member_products);
            /* echo '客户预存信息修改到此接收----88888';echo '<br/>';
            var_dump($aaa); */
            // exit;

            //----------------------------处理客户K3信息-----------------------------

            $shop_id = $data['shop_id'];

            $where = [];

            array_push($where,['shop_id','=',$shop_id]);

            $shop = Db::name('shop')->where($where)->find();

            //echo '客户预存信息修改到此接收----111111111111';echo '<br/>';

            if ($shop['type'] != 2) {

                $res = $customerModel->pushKingCustomer($customer_id);
                // echo "1";echo "<br/>";
                // var_dump($res);
                // exit;
                //echo '客户预存信息修改到此接收----333333333333';echo '<br/>';
                if ($res == false) {

                    // $this->error = $customerModel->getError();

                    return $this->error = $customerModel->getError();

                }

                ////////////////////////////////////////////////////////////////////////////////////////
                $mark4 = bcadd($data['mark4'],1,0);

                $whereMark4 = [];

                array_push($whereMark4,['id','=',$data['id']]);

                $save4 = [
                    'mark4' => $mark4,
                ];

                Db::name('shop_refund_order')->where($whereMark4)->update($save4);
                //////////////////////////////////////////////////////////////////////////////////////////////


                // 屏蔽金蝶推送
                $kingDee = new Kingdee();

                //收款单
                //echo '客户预存信息修改到此接收----444444444';echo '<br/>';
                if ($data['type']==3)

                {

                    ////////////////////////////////////////////////////////////////////////////////////////
                    $mark5 = bcadd($data['mark5'],1,0);

                    $whereMark5 = [];

                    array_push($whereMark5,['id','=',$data['id']]);

                    $save5 = [
                        'mark5' => $mark5,
                    ];

                    Db::name('shop_refund_order')->where($whereMark5)->update($save5);
                    //////////////////////////////////////////////////////////////////////////////////////////////

                    $result=$kingDee->receipt_money($data['id']);

                }else{

                    //退款单

                    $result=$kingDee->refund_money($data['id']);

                }
                //echo '客户预存信息修改到此接收----555555555555';echo '<br/>';
                // echo "2";echo "<br/>";
                // var_dump($result);
                // exit;

                if ($result['code']!='0')

                {

                    return $this->error = $result['msg'];

                    // return false;

                }


            }

            //echo '客户预存信息修改到此接收----77777777777777755555584';echo '<br/>';
            Db::commit();

            $this->error = '创建成功';

            return true;

        } catch (\Exception $e) {

            Db::rollback();

            $msg = "";
            foreach ($data as $key => $value)
            {
                $msg.="[".$key."=>".$value."],";
            }
            $msg.="\n";
            $fp = fopen("./storage/log.txt", 'ab'); // 打开最终文件
            fwrite($fp, $msg); // 写入到最终文件
            fclose($fp); // 关闭最终文件

            $this->error = $e->getMessage();

            return false;

        }





    }


}
